﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using QuickJob.forms;
using System.IO;
using System.Text.RegularExpressions;

namespace QuickJob.lib
{
        /// <summary>
        /// 一行字体的保存
        /// </summary>
        public class DropConfigItemRow{
        

            /// <summary>
            /// 文本
            /// </summary>
            public string text;

            /// <summary>
            /// 颜色
            /// </summary>
            public Color color;

          
            /// <summary>
            /// 字休格式
            /// </summary>
            public Font font;


            /// <summary>
            /// 字体位置　
            /// </summary>
            public Point location;


            /// <summary>
            /// 克隆
            /// </summary>
            /// <returns></returns>
            public DropConfigItemRow Clone()
            {
                DropConfigItemRow row = new DropConfigItemRow();
                try
                {

                    row.text = (string)text.Clone();
                    row.color = Color.FromArgb(color.ToArgb());
                    row.font = new Font(font.FontFamily, font.Size, font.Style);
                    row.location = new Point(location.X, location.Y);
                    return row;
                }
                catch { }

                return row;
            }


        }


        /// <summary>
        /// 一个配置项
        /// </summary>
        public class DropConfigItem {

            public string ConfigName;


            public DropConfigItemRow PingMing;

            public DropConfigItemRow KuanHao;

            public DropConfigItemRow BuLiao;


            /// <summary>
            /// 图片路径
            /// </summary>
            public string imgDir;

            public DropConfigItem()
            {
                PingMing = new DropConfigItemRow();
                KuanHao = new DropConfigItemRow();
                BuLiao = new DropConfigItemRow();
            }


            /// <summary>
            /// 克隆
            /// </summary>
            /// <returns></returns>
            public DropConfigItem Clone()
            {
                DropConfigItem i = new DropConfigItem();
                try
                {
                    i.ConfigName = (string)ConfigName.Clone();
                    i.PingMing = PingMing.Clone();
                    i.KuanHao = KuanHao.Clone();
                    i.BuLiao = BuLiao.Clone();
                    i.imgDir = (string)imgDir.Clone();


                }
                catch { }
                return i;
            }
        
        }


        /// <summary>
        /// 配置文件操作
        /// </summary>
        public class Config
        {


            /// <summary>
            /// 数据文件
            /// </summary>
            String filename = "dropconfig.ini";
            String fileData = null;
            List<String> _lines = new List<String>();
            String line
            {
                get
                {
                    if (_lines.Count > 0)
                        return _lines[_lines.Count - 1];
                    else return null;
                }
                set { fileData += value + "\r\n"; _lines.Add(value); }
            }

            /// <summary>
            /// 电表数据
            /// </summary>
            public List<DropConfigItem> clist = new List<DropConfigItem>();


            /// <summary>
            /// 保存配置
            /// </summary>
            /// <param name="d"></param>
            /// <returns></returns>
            public int SaveConfig(List<String> d)
            {
                StreamWriter rd;
                int count = 0;
                String fn = System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + filename;
                try
                {

                    rd = new StreamWriter(fn, false, Encoding.Default);
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("SaveConfig无法打开:" + fn);
                    MessageBox.Show("SaveConfig无法打开文件" + fn);
                    return -1;
                }


                //写入文件
                int i = 0;
                for (i = 0; i < d.Count; i++)
                {
                    rd.WriteLine(d[i]);
                }


                rd.Close();



                return count;
            }


            /// <summary>
            /// 读取电表配置，返回配置个数
            /// </summary>
            /// <returns></returns>
            public int ReadConfig()
            {

                StreamReader rd;
                String fn = System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + filename;
                try
                {

                    rd = new StreamReader(fn, Encoding.Default);
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("logSettingRecover无法打开:" + fn);
                    MessageBox.Show("logSettingRecover无法打开文件" + fn);
                    return -1;
                }




                /*
                    配置形式
                    +ConfigName="A字裤"
                    +//       字符串　　颜色　　　字体　大小　　位置
                    +PingMing="A字裤","FF400000","仿宋","20","100-100"
                    +KuanHao="W0038","FFFF0000","仿宋","20","100-200"
                    +BuLiao="棉60%  \r\n\r\n  聚酯纤维40%","FFFFFFFF","黑体","20","100-400"
                    +</config>
                 */

                _lines.Clear();

                ///读入文件
                for (line = rd.ReadLine(); line != null; line = rd.ReadLine())
                { }
                rd.Close();

                ///搜索配置
                clist = GetConfigAll(_lines);

                return this.clist.Count;

            }



            #region   配置操作

            //一个匹配项
            public class MatchString
            {
                public string patten;
                public Match m;
                public int index;

                public MatchString() { patten = null; m = null; index = -1; }
                public MatchString(string p, Match mm, int i) { patten = p; m = mm; index = i; }
            }
            /// <summary>
            /// 读取配置项
            /// </summary>
            /// <param name="s"></param>
            /// <param name="patten"></param>
            /// <param name="startline"></param>
            /// <param name="endline"></param>
            /// <returns></returns>
            private MatchString GetLine(List<String> s, string patten, int startline, int endline)
            {
                MatchString ms = new MatchString(patten, null, -1);

                if (endline > s.Count) endline = s.Count;
                if (s == null || s.Count < +startline) return ms;
                int i = 0;
                Match m;
                for (i = startline; i < s.Count; i++)
                {
                    if (s[i] == null) continue;
                    m = Regex.Match(s[i], patten);
                    if (m != null && m.Success)
                    {
                        ms.m = m;
                        ms.index = i;
                        return ms;
                    }

                }

                return ms;
            }



            class ConfigInfo
            {
                public DropConfigItem item;
                public MatchString startline;
                public MatchString endline;

                public ConfigInfo() { item = null; startline = null; endline = null; }
            }


            /// <summary>
            /// 从数据中读取所有的配置信息
            /// </summary>
            /// <param name="fildLines"></param>
            /// <returns></returns>
            public List<DropConfigItem> GetConfigAll(List<String> fileLines)
            {
                List<DropConfigItem> LDropConfigItem = new List<DropConfigItem>();
                if (fileLines == null || fileLines.Count < 2) return LDropConfigItem;

                ///读取一个配置　
                {
                        MatchString startline = new MatchString(null, null, 0), endline = new MatchString(null, null, 0);
                        while (_lines.Count > 0 && (startline = GetLine(_lines, @"<Config>", endline.index, _lines.Count)).index >= 0)
                        {
                            if ((endline = GetLine(_lines, @"</Config>", startline.index, _lines.Count)).index <= startline.index)
                                break;


                            //在<config> </config>找configname
                            MatchString _nameline = GetLine(_lines, @"ConfigName=(\S|\s)*", startline.index, endline.index);

                            //找到
                            if (_nameline.m != null && _nameline.m.Success) {

                                DropConfigItem item = new DropConfigItem();

                                //ConfigName
                                try {
                                    Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None);
                                    item.ConfigName = re.Match(_nameline.m.Value).Value;
                                }
                                catch { }
                                //PingMing
                                try {
                                    MatchString pingMingLine = GetLine(_lines, @"PingMing=(\S|\s)*", startline.index, endline.index);
                                    Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None);
                                    MatchCollection pingMingMatchCollection = re.Matches(pingMingLine.m.Value);
                                    //MatchCollection pingMingMatchCollection = Regex.Matches(pingMingLine.m.Value, "\"[^\"]*\"");
                                    item.PingMing.text = pingMingMatchCollection[0].Value.Replace("\\r\\n", "\r\n");
                                    item.PingMing.color = Color.FromArgb(int.Parse(pingMingMatchCollection[2].Value,System.Globalization.NumberStyles.HexNumber));
                                    item.PingMing.font = new Font(pingMingMatchCollection[4].Value,
                                        float.Parse(pingMingMatchCollection[6].Value), FontStyle.Regular);
                                    string[] pingMingLocation = pingMingMatchCollection[8].Value.Split('-');
                                    item.PingMing.location = new Point(int.Parse(pingMingLocation[0]), int.Parse(pingMingLocation[1]));
                                }
                                catch { }
                                //KuanHao
                                try
                                {
                                    MatchString kuanHaoLine = GetLine(_lines, @"KuanHao=(\S|\s)*", startline.index, endline.index);
                                    Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None);
                                    MatchCollection kuanHaoMatchCollection = re.Matches(kuanHaoLine.m.Value);
                                    //MatchCollection kuanHaoMatchCollection = Regex.Matches(kuanHaoLine.m.Value, "\"[^\"]*\"");
                                    item.KuanHao.text = kuanHaoMatchCollection[0].Value.Replace("\\r\\n", "\r\n");
                                    item.KuanHao.color = Color.FromArgb(int.Parse(kuanHaoMatchCollection[2].Value, System.Globalization.NumberStyles.HexNumber));
                                    item.KuanHao.font = new Font(kuanHaoMatchCollection[4].Value,
                                        float.Parse(kuanHaoMatchCollection[6].Value), FontStyle.Regular);
                                    string[] kuanHaoLocation = kuanHaoMatchCollection[8].Value.Split('-');
                                    item.KuanHao.location = new Point(int.Parse(kuanHaoLocation[0]), int.Parse(kuanHaoLocation[1]));
                                }
                                catch { }
                                //BuLiao
                                try
                                {
                                    MatchString BuLiaoLine = GetLine(_lines, @"BuLiao=(\S|\s)*", startline.index, endline.index);
                                    Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None);
                                    MatchCollection BuLiaoMatchCollection = re.Matches(BuLiaoLine.m.Value);
                                    //MatchCollection BuLiaoMatchCollection = Regex.Matches(BuLiaoLine.m.Value, "\"[^\"]*\"");
                                    item.BuLiao.text = BuLiaoMatchCollection[0].Value.Replace("\\r\\n","\r\n");
                                    item.BuLiao.color = Color.FromArgb(int.Parse(BuLiaoMatchCollection[2].Value, System.Globalization.NumberStyles.HexNumber));
                                    item.BuLiao.font = new Font(BuLiaoMatchCollection[4].Value,
                                        float.Parse(BuLiaoMatchCollection[6].Value), FontStyle.Regular);
                                    string[] BuLiaoLocation = BuLiaoMatchCollection[8].Value.Split('-');
                                    item.BuLiao.location = new Point(int.Parse(BuLiaoLocation[0]), int.Parse(BuLiaoLocation[1]));
                                }
                                catch { }


                                //img dir

                                try
                                {
                                    MatchString imgdir = GetLine(_lines, @"img=(\S|\s)*", startline.index, endline.index);
                                    Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None);
                                    MatchCollection imgc = re.Matches(imgdir.m.Value);
                                    item.imgDir = imgc[0].Value;
                                }
                                catch { }

                                LDropConfigItem.Add(item);
                            }

                        }
                    return LDropConfigItem;
                }


            }



            /// <summary>
            /// 取得配置的信息,主要是读取开始结尾行
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
            ConfigInfo GetConfigInfo(DropConfigItem item)
            {
                if (item == null) return null;
                ConfigInfo info = new ConfigInfo();
                {
                    MatchString startline = new MatchString(null, null, 0), endline = new MatchString(null, null, 0);
                    while (_lines.Count > 0 && (startline = GetLine(_lines, @"<Config>", endline.index, _lines.Count)).index >= 0)
                    {
                        if ((endline = GetLine(_lines, @"</Config>", startline.index, _lines.Count)).index <= startline.index) return null;


                        //在<config> </config>找configname
                        MatchString _nameline = GetLine(_lines, @"ConfigName=(\S|\s)*", startline.index, endline.index);
                        if (_lines[_nameline.index] != string.Format("ConfigName=\"{0}\"", item.ConfigName))
                            continue;

                        //找到
                        info.startline = startline;
                        info.endline = endline;
                        info.item = item;
                        return info;
                    }
                }

                return null;
            }


            /// <summary>
            /// 修改配置  startline = endline == -1 ，时，在后面　追加一个配置
            /// </summary>
            /// <param name="startline"></param>
            /// <param name="endline"></param>
            /// <param name="newitem"></param>
            public bool DropConfigItemAddAt(int startline,int endline, DropConfigItem newitem)
            {
                ///添加空行
                if (startline == -1 && endline == -1)
                {
                    startline = _lines.Count;
                    endline = _lines.Count + 7;

                    //虚拟一个项

                    _lines.Add("<Config>");
                    _lines.Add("ConfigName=1");
                    _lines.Add("PingMing=2");
                    _lines.Add("KuanHao=3");
                    _lines.Add("BuLiao=4");
                    _lines.Add("img=5");              
                    _lines.Add("</Config>");

                }

                //添加配置
                MatchString m;
                try
                {

                    //////////////////////////////////////////////////////////////////////////
                    //修改配置名
                    m = GetLine(_lines, @"ConfigName=(\S|\s)*", startline, endline);
                    _lines[m.index] = "ConfigName=\"" + newitem.ConfigName + "\"";


                    //pingming
                    m = GetLine(_lines, @"PingMing=(\S|\s)*", startline, endline);
                    _lines[m.index] = string.Format(
                        "PingMing=\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}-{5}\"",
                        newitem.PingMing.text.Replace("\r\n", "\\r\\n"),
                        Ulitily.ShareClass.Hex32ToString((UInt32)newitem.PingMing.color.ToArgb()),
                        newitem.PingMing.font.FontFamily.Name.ToString(),
                        newitem.PingMing.font.Size,
                        newitem.PingMing.location.X,
                        newitem.PingMing.location.Y);

                    //kuanhao
                    m = GetLine(_lines, @"KuanHao=(\S|\s)*", startline, endline);
                    _lines[m.index] = string.Format(
                        "KuanHao=\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}-{5}\"",
                        newitem.KuanHao.text.Replace("\r\n", "\\r\\n"),
                        Ulitily.ShareClass.Hex32ToString((UInt32)newitem.KuanHao.color.ToArgb()),
                        newitem.KuanHao.font.FontFamily.Name.ToString(),
                        newitem.KuanHao.font.Size,
                        newitem.KuanHao.location.X,
                        newitem.KuanHao.location.Y);

                    //buliao
                    m = GetLine(_lines, @"BuLiao=(\S|\s)*", startline, endline);
                    _lines[m.index] = string.Format(
                        "BuLiao=\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}-{5}\"",
                        newitem.BuLiao.text.Replace("\r\n", "\\r\\n"),
                        Ulitily.ShareClass.Hex32ToString((UInt32)newitem.BuLiao.color.ToArgb()),
                        newitem.BuLiao.font.FontFamily.Name.ToString(),
                        newitem.BuLiao.font.Size,
                        newitem.BuLiao.location.X,
                        newitem.BuLiao.location.Y);

                    //dir
                    m = GetLine(_lines, @"img=(\S)*", startline, endline);
                    _lines[m.index] = string.Format(
                        "img=\"{0}\"", newitem.imgDir);

                    //save all data
                    SaveConfig(_lines);

                    ReadConfig();

                    return true;
                }
                catch
                {

                    System.Console.WriteLine("保存配置失败: new:{0}", newitem.ConfigName);

                    return false;

                }

                return false;
            }
            /// <summary>
            /// 保存一个配置,原配置不存在，追加
            /// </summary>
            /// <param name="olditem"></param>
            /// <param name="newitem"></param>
            /// <returns></returns>
           public  bool SaveDropConfigItem(DropConfigItem olditem, DropConfigItem newitem)
            {
                ConfigInfo info = GetConfigInfo(olditem);
                if (info == null) return DropConfigItemAddAt(-1, -1, newitem);
                else return DropConfigItemAddAt(info.startline.index, info.endline.index, newitem);
            }


            /// <summary>
            /// 删除配置
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
           public bool DeleteDropConfigItem(DropConfigItem item)
           {
               ConfigInfo info = GetConfigInfo(item);

               if (info != null) {

                   int len = info.endline.index - info.startline.index;
                   while (len > 0) {
                       _lines.RemoveAt(info.startline.index);
                       len--;
                   }

                   SaveConfig(_lines);
                   ReadConfig();

                   return true;
               
               }

               return true;
           }
            
            
            #endregion
        }




    /// <summary>
    /// 配置显示类，使用pictureBox
    /// </summary>
    public class DropConfigView:Label
    {

        public string ConfigName;

        /// <summary>
        /// 图片路径
        /// </summary>
        public string pictureDir;

        /// <summary>
        /// 品名
        /// </summary>
        public TextBoxExt pingMing = new TextBoxExt();



        /// <summary>
        /// 款名
        /// </summary>
        public TextBoxExt kuanHao = new TextBoxExt();

        /// <summary>
        /// 布料
        /// </summary>
        public TextBoxExt buLiao = new TextBoxExt();


        /// <summary>
        /// 用于画图
        /// </summary>
        PictureBox _pictureBox = null;



        public DropConfigView(DropConfigItem cfgitem,PictureBox pictureBox)
        {

            pictureDir = cfgitem.imgDir;
            ConfigName = cfgitem.ConfigName;

            pictureBox.Image = Image.FromFile(cfgitem.imgDir);

            pingMing.SuspendLayout();
            kuanHao.SuspendLayout();
            buLiao.SuspendLayout();
            pictureBox.SuspendLayout();

            pingMing.Enabled = true;
            kuanHao.Enabled = true;
            buLiao.Enabled = true;



            pingMing.Location = cfgitem.PingMing.location;
            pingMing.Font = cfgitem.PingMing.font;
            pingMing.ForeColor = cfgitem.PingMing.color;
            pingMing.Text = cfgitem.PingMing.text;

            kuanHao.Location = cfgitem.KuanHao.location;
            kuanHao.Font = cfgitem.KuanHao.font;
            kuanHao.ForeColor = cfgitem.KuanHao.color;
            kuanHao.Text = cfgitem.KuanHao.text;
           
         
            buLiao.Location = cfgitem.BuLiao.location;       
            buLiao.Font = cfgitem.BuLiao.font;
            buLiao.ForeColor = cfgitem.BuLiao.color;
            buLiao.Text = cfgitem.BuLiao.text;


            pictureBox.Controls.Add(pingMing);
            pictureBox.Controls.Add(kuanHao);
            pictureBox.Controls.Add(buLiao);

            pingMing.BorderStyle = BorderStyle.None;
            kuanHao.BorderStyle = BorderStyle.None;
            buLiao.BorderStyle = BorderStyle.None;

            
            pictureBox.Size = pictureBox.Image.Size;

            _pictureBox = pictureBox ;


            //双击选择字体
            pingMing.ResumeLayout();
            kuanHao.ResumeLayout();
            buLiao.ResumeLayout();
            pictureBox.ResumeLayout();


           
        }




        //////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// 转换为 DropConfigItem格式 
        /// </summary>
        /// <returns></returns>
        public DropConfigItem ToDropConfigItem()
        {
            DropConfigItem item = new DropConfigItem();

            item.ConfigName = ConfigName;

            item.PingMing.text = pingMing.Text;
            item.PingMing.font = pingMing.Font;
            item.PingMing.color = pingMing.ForeColor;
            item.PingMing.location = pingMing.Location;



            item.KuanHao.text = kuanHao.Text;
            item.KuanHao.font = kuanHao.Font;
            item.KuanHao.color = kuanHao.ForeColor;
            item.KuanHao.location = kuanHao.Location;



            item.BuLiao.text = buLiao.Text;
            item.BuLiao.font = buLiao.Font;
            item.BuLiao.color = buLiao.ForeColor;
            item.BuLiao.location = buLiao.Location;


            item.imgDir = pictureDir;

            return item;

        }


        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="FileDirectory">文件路径</param>
        /// <param name="FileName">文件名</param>
        /// <returns></returns>
        public Bitmap  SaveBmp(string FileDirectory,string FileName)
        {
            if (_pictureBox != null)
            {
                Bitmap b = new Bitmap(_pictureBox.Size.Width, _pictureBox.Size.Height);
                _pictureBox.Update();
                _pictureBox.DrawToBitmap(b, new Rectangle(0, 0, _pictureBox.Size.Width, _pictureBox.Size.Height));
                b.Save(System.IO.Path.Combine(FileDirectory, FileName));
                return b;
            }

            return null;
        }
    }



}
